<template>
  <div class="w-breadcrumbs" :class="classes">
    <template v-for="(item, i) in items"
      ><span
        class="w-breadcrumbs__separator"
        v-if="i && $slots.separator"
        :key="`${i}-1`"
        :class="separatorColor"
      >
        <slot name="separator" :index="i"></slot>
      </span>
      <w-icon
        class="w-breadcrumbs__separator"
        v-else-if="i"
        :key="`${i}-2`"
        :class="separatorColor"
        >{{ icon }}</w-icon
      >
      <template
        v-if="item[itemRouteKey] && (i < items.length - 1 || linkLastItem)"
      >
        <component
          class="w-breadcrumbs__item"
          v-if="$slots.item"
          :key="`${i}-3`"
          :is="hasRouter ? 'router-link' : 'a'"
          :to="hasRouter && item[itemRouteKey]"
          :href="item[itemRouteKey]"
          :class="color || null"
        >
          <slot
            name="item"
            :item="item"
            :index="i + 1"
            :isLast="i === items.length - 1"
          ></slot>
        </component>
        <component
          class="w-breadcrumbs__item"
          v-else
          :key="`${i}-4`"
          :is="hasRouter ? 'router-link' : 'a'"
          :to="hasRouter && item[itemRouteKey]"
          :href="item[itemRouteKey]"
          v-html="item[itemLabelKey]"
          :class="color || null"
        ></component>
      </template>
      <slot
        v-else-if="$slots.item"
        name="item"
        :item="item"
        :index="i + 1"
        :isLast="
          /* Vue3 camelcase issue: https://github.com/vuejs/vue-next/issues/2488 */ i ===
            items.length - 1
        "
      ></slot
      ><span v-else :key="`${i}-5`" v-html="item[itemLabelKey]"></span>
    </template>
  </div>
</template>

<script>
import { computed, getCurrentInstance } from "vue";
export default {
  name: "w-breadcrumbs",
  props: {
    items: { type: Array, required: true },
    linkLastItem: { type: Boolean },
    color: { type: String }, // Applies on links.
    separatorColor: { type: String, default: "grey-light1" },
    icon: { type: String, default: "wi-chevron-right" },
    itemRouteKey: { type: String, default: "route" },
    itemLabelKey: { type: String, default: "label" },
    xs: { type: Boolean },
    sm: { type: Boolean },
    md: { type: Boolean },
    lg: { type: Boolean },
    xl: { type: Boolean }
  },

  emits: [],
  setup(props) {
    const instance = getCurrentInstance();
    const hasRouter = computed(() => {
      return "$router" in instance.ctx;
    });
    const size = computed(() => {
      return (
        (props.xs && "xs") ||
        (props.sm && "sm") ||
        (props.lg && "lg") ||
        (props.xl && "xl") ||
        "md"
      );
    });
    const classes = computed(() => {
      return {
        [`size--${size.value}`]: true
      };
    });
    return {
      hasRouter,
      size,
      classes
    };
  }
};
</script>

<style lang="scss">

</style>
